<script setup lang="ts">
import { loginAPI, tokenAPI, loginAPI1 } from '@/services/my'
import { loginAPIhou } from '@/services/my copy'
import type { mylogin } from '@/types/my'
import { ref, onMounted, computed } from 'vue'
import { myStore } from '@/stores'
import { useMemberStore } from '@/stores'
import { onLoad, onShow } from '@dcloudio/uni-app'
import heard from './compoments/heard/index.vue'
// declare props and emitted events using pure TypeScript
// reactive state
const user = ref<any>({})
const information = ref<any>({
  username: '',
  password: '',
})

// 跳转注册==================
const zhuci = () => {
  uni.navigateTo({ url: '../zhuche/index' })
}
// ==============================
const form = ref()

const rules = ref<any>({
  // 对name字段进行必填验证
  username: {
    rules: [
      {
        required: true,
        errorMessage: '请输入姓名',
      },
      {
        minLength: 3,
        maxLength: 15,
        errorMessage: '姓名长度在 {minLength} 到 {maxLength} 个字符',
      },
    ],
  },
  // 对email字段进行必填验证
  password: {
    rules: [
      {
        required: true,
        errorMessage: '请输入密码',
      },
      {
        minLength: 5,
        maxLength: 15,
        errorMessage: '密码长度在 {minLength} 到 {maxLength} 个字符',
      },
    ],
  },
})
// 协议=============================================================
const xieyii = ref(false)
const xieyi1 = () => {
  xieyii.value = true
}
// 协议功能
const xieyi = () => {
  uni.showModal({
    title: '提示',
    confirmText: '同意',
    content:
      '您认为不必要的信息可直接忽略，本平台所有信息均用于报名。您发出的名片中只显示您的“姓名、手机、公司、职位和简介”，若涉及您的隐私，请谨慎使用您的名片功能。',
    success: function (res) {
      if (res.confirm) {
        // 执行确认后的操作
        uni.showToast({
          title: '收到协议回复',
          //将值设置为 success 或者直接不用写icon这个参数
          icon: 'success',
          //显示持续时间为 2秒
          duration: 1000,
        })
      } else {
        // 执行取消后的操作
        uni.showToast({
          title: '取消成功',
          //将值设置为 success 或者直接不用写icon这个参数
          icon: 'error',
          //显示持续时间为 2秒
          duration: 3000,
        })
      }
    },
  })
  var options = {
    success: function (response) {
      console.log('success  ' + JSON.stringify(response))
      if (response.code == 1) {
        //用户已同意隐私政策，可以使用其它业务功能
        // plus.runtime.restart();
      } else {
        //用户未同意隐私政策，仍然运行disagreeMode模式，不可以使用其它业务功能
        // ...
      }
    },
    fail: function (response) {
      console.log('fail  ' + JSON.stringify(response))
    },
  }
  //弹出隐私政策协议框，引导用户同意隐私政策
  plus.runtime.showPrivacyDialog(options)
}
// ================================================================================
// 校验功能

const usernameError = computed(() => {
  if (information.value.username.length === 0) {
    return '请填写姓名'
  } else if (information.value.username.length > 10) {
    return '姓名长度不能超过10个字符'
  }
  return ''
})

const passwordError = computed(() => {
  if (information.value.password.length === 0) {
    return '请填写密码'
  } else if (information.value.password.length > 11) {
    return '密码长度不能超过11个字符'
  }
  return ''
})
// ///////////////////
const flag = ref<any>(true)

// // onShow hook
// onMounted(() => {
//   // console.log('ref', $refs)
//   wx.getStorage({
//     key: 'openid',
//     success(res) {
//       // 跳转userInform方法，传入openid进行查询用户信息
//       userInform(res.data)
//     },
//   })
// })
const mylogin1 = myStore()
const member = useMemberStore()
// methods
function onName(event: Event) {
  console.log(event)
  information.value.username = (event.target as HTMLInputElement).value
}

function password(event: Event) {
  console.log(event)
  information.value.password = (event.target as HTMLInputElement).value
}

async function upInfo() {
  form.value
    .validate()
    .then(async (res1) => {
      console.log('表单数据信息：', res1)

      if (xieyii.value == true) {
        //前端数据请求时，显示加载提示弹框
        uni.showLoading({
          title: '加载中...',
        })
        // if (information.value.uesrname == '' || information.value.password == '') {
        //   uni.showToast({
        //     title: '内容不能为空哦！',
        //     icon: 'none',
        //   })
        //   return
        // }
        // 点击上传信息按钮触发的方法
        const bannerList = ref<mylogin>()
        console.log(information.value)
        // const res = await loginAPI(information.value)
        const res = await loginAPIhou(information.value)
        bannerList.value = res.data
        console.log(res)
        //将服务器图片放进  本地去就可以获取图片
        mylogin1.setuserinfo(bannerList.value)
        console.log(mylogin1.userinfo.picAddress, '6666666')

        // 获取token
        const token = res.data?.token

        console.log(token)

        member.setProfile(bannerList.value)
        member.upProfile(token)

        // 数据从后端接口返回后，提示弹框关闭
        uni.hideLoading()
        if (res.code == '1') {
          // uni.switchTab({
          //   url: '../my/my',
          // })
          // 跳转其他页面
          uni.navigateTo({
            url: '../../pagesA/xuanzhe/index',
          })


          uni.showToast({
            title: '登陆成功',
            //将值设置为 success 或者直接不用写icon这个参数
            icon: 'success',
            //显示持续时间为 2秒
            duration: 2000,
          })
        } else {
          uni.showToast({
            title: '登录失败',
            //将值设置为 success 或者直接不用写icon这个参数
            icon: 'error',
            //显示持续时间为 2秒
            duration: 3000,
          })
          // 数据从后端接口返回后，提示弹框关闭
          uni.hideLoading()
        }
      } else {
        uni.showToast({
          title: '请打钩协议',
          //将值设置为 success 或者直接不用写icon这个参数
          icon: 'error',
          //显示持续时间为 2秒
          duration: 2000,
        })
      }
    })
    .catch((err) => {
      console.log('表单错误信息：', err)
      uni.showToast({
        title: '校验失败',
        //将值设置为 success 或者直接不用写icon这个参数
        icon: 'error',
        //显示持续时间为 2秒
        duration: 2000,
      })
    })

  // 成功后跳转到 个人中心
}

// 实现微信登录=====================================================
const localtoken = ref<any>('')
const code = ref<any>()
onShow(() => {
  localtoken.value = member.token
})

const getUserInfo = () => {
  uni.showLoading({
    // 展示加载框

    title: '加载中',
    image: '../../static/images/loading 加载中_爱给网_aigei_com.gif',
  })

  // 获取用户信息 微信登录
  uni.getUserProfile({
    desc: '登录后可同步数据',
    success: async (obj) => {
      console.log(obj)
      information.value.uesrname = obj.userInfo.nickName
      // 只能通过pinia 进行数据交互
      mylogin1.setuserinfo({ picAddress: obj.userInfo.avatarUrl, username: obj.userInfo.nickName })

      uni.login({
        provider: 'weixin',
        success: async (res) => {
          console.log('res-login', res)
          // 获取code
          code.value = res.code
          console.log('这个code是', code.value)
          // 我可以向后端进行请求接口登录
          // 请求登录的状态是登录
          if (res.errMsg == 'login:ok') {
            let params = {
              code: code.value,
              nickname: information.value.username,
              avatar: mylogin1.userinfo.picAddress,
              appid: 'wxc35416933026b817',
              userProfile: obj,
              appSecret: '46682f6435b6b1ac8393a22f5e903d93',
            }
            let res = await loginAPI1(params)
            console.log(res, '接受到什么数据')
            console.log('666666666666666666666666666')

            if (res.code == '1') {
              uni.showToast({
                title: '登录成功',
                icon: 'success',
                mask: true,
              })
              // 登录后获取token  假设token
              member.upProfile(res.data.openid)
              //  将openid 和 sessionkey存进pinia中
              // 后续可以操作把  头像和名字都 存进pinia中就可以显示出来，mylogin1.setuserinfo({ picAddress: obj.userInfo.avatarUrl })
              mylogin1.setOpenid(res.data.openid)
              mylogin1.setSessionkey(res.data.sessionkey)
              // 跳转页面即可
              uni.switchTab({
                url: '../my/my',
              })
            } else {
              uni.showToast({
                title: '登录失败',
                icon: 'error',
                mask: true,
                //显示持续时间为 2秒
                duration: 5000,
              })
            }
          }
        },
        fail: () => {
          uni.showToast({
            title: '授权已取消',
            icon: 'error',
            mask: true,
            //显示持续时间为 2秒
            duration: 5000,
          })
        },
        complete: () => {
          console.log('执行隐藏')

          // 隐藏loading
          uni.hideLoading()
        },
      })
    },
  })
}

// ================================================================
</script>

<template>
  <view class="user">
    <view class="zhidon">
      <view class="beizi">
        <heard class="heard" />
        <!-- <view class="uni-common-mt">
      <view class="uni-form-item uni-column user-input">
        <view class="title">姓名</view>
        <view class="input">
          <input
            class="uni-input"
            @input="onName"
            :value="information.username"
            maxlength="12"
            placeholder="我们对您的称呼"
          />
        </view>
      </view>
      <view v-if="usernameError" class="error-message">{{ usernameError }}</view>
      <view class="uni-form-item uni-column user-input">
        <view class="title">密码</view>
        <view class="input">
          <input
            class="uni-input"
            :type="flag ? 'password' : 'text'"
            @input="password"
            :value="information.password"
            maxlength="15"
            placeholder="我们可以成功与您沟通的联系方式"
          />

          <image :src="url" mode="scaleToFill" style="width: 50rpx; height: 56rpx" @tap="vision" />
        </view>
      </view>
      <view v-if="passwordError" class="error-message">{{ passwordError }}</view>
    </view>-->
        <!-- ----------------------------------------------------------------------------------------============ -->
        <view>
          <uni-forms ref="form" :modelValue="information" :rules="rules" class="uni-common-mt">
            <uni-forms-item label="姓名" name="username" class="custom-label-width">
              <uni-easyinput
                type="nickname"
                v-model="information.username"
                placeholder="请输入姓名"
              />
            </uni-forms-item>
            <uni-forms-item label="密码" name="password" class="user-input1">
              <uni-easyinput
                :type="flag ? 'password' : 'text'"
                v-model="information.password"
                placeholder="请输入密码"
              />
              <!--     <image
            :src="url"
            mode="scaleToFill"
            style="width: 50rpx; height: 56rpx"
            @tap="vision"
            class="eye"
          /> -->
            </uni-forms-item>
          </uni-forms>
          <!-- 注册 和忘记密码  -->
          <view class="zhuce">
            <navigator @tap="zhuci">立即注册</navigator>
            <navigator>忘记密码?</navigator>
          </view>
          <!-- 协议区  xieyi -->
          <view class="xieyi">
            <checkbox class="isXY" @tap="xieyi1"></checkbox>
            <view class="text-xy" @tap="xieyi">同意小程序的《使用协议》</view>
          </view>
        </view>

        <!-- ============================================================================================= -->

        <button class="up-button" @click="upInfo()">发送登录</button>

        <!-- 提示框  使用以下方式登录 -->
        <view class="v3">
          <view class="line"></view>
          <view class="lText">您还可以使用以下方式登录</view>
          <view class="line"></view>
        </view>
        <!-- qq  weixin  weibo 图标展示view -->
        <view class="qwwIcon">
          <image src="./images/weixin.png" class="weixin" @tap="getUserInfo" />
          <image src="./images/qq.png"></image>
          <image src="./images/weibo.png"></image>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.uni-easyinput {
  font-size: 140px;
}
page {
  background: linear-gradient(to right, rgb(0, 225, 255), rgb(192, 207, 255));
}
.zhidon {
  width: 900rpx;
  background: #f0eaea;
  display: flex;

  left: 100rpx;
}
.beizi {
  position: relative;
  background: #f0eaea;
  border-radius: 50rpx;
  width: 700rpx;
  height: 900rpx;
  left: 100rpx;
}
.user {
  height: 800px;
  display: flex;
  /*垂直排列*/
  flex-direction: column;
  align-items: center; /*由于flex-direction: column，因此align-items代表的是水平方向*/
  justify-content: center;
}

.user-input {
  position: relative;
  width: 335px;
  height: 50px;
  margin: 20px auto;
  justify-content: center;
  align-items: center;
  display: flex;
  border-style: solid;
  border-color: rgb(240, 228, 228);
  border-width: 1px;
  .input {
    width: 280px;
    margin-left: 20px;
  }
}
.user-input1 {
  display: flex;
}

.fenjie {
  width: 335px;
  height: 1px;
  background: #ddd;
  margin: 0 auto;
}

.up-button {
  width: 160px;
  height: 40px;
  background: linear-gradient(to right, rgb(0, 225, 255), pink);
  border-radius: 4px;
  font-size: 16px;
  line-height: 40px;
  color: white;
  margin-top: 30px;
}

.notes {
  width: 335px;
  margin: 20px auto 50px;
  font-size: 14px;

  .aa {
    color: red;
    margin-right: 4px;
  }
}
.input {
  display: flex;
  justify-content: center;
}
.input image {
  position: relative;
  right: -25px;
  top: 16px;
  transform: translateY(-50%);
}
// 校验样式

.error-message {
  font-size: 20px;
  color: red;
  margin-top: 4px;
}
.eye {
  position: relative;
  right: -180px;
  top: -30px;
}

// 小图标
.qwwIcon {
  margin-top: 100rpx;
  padding-top: 30rpx;
  position: relative;
  display: flex;

  justify-content: space-between;
  width: 100%;
  height: 150rpx;
}
.qwwIcon image {
  padding-left: -120rpx;
  width: 80rpx;
  height: 80rpx;
}
/* 提示文本 */
.v3 {
  padding-left: 100rpx;
  display: flex;
  position: relative;
  width: 100%;
  height: 60rpx;
  padding-top: 50rpx;
}
.v3 .line {
  margin-left: 5rpx;
  margin-top: 18rpx;
  width: 120rpx;
  height: 3rpx;
  background-color: #120808;
}
.v3 .lText {
  color: #130606;
  font-size: 25rpx;
}

.zhuce {
  font-size: 20rpx;
  margin-left: 100rpx;
  width: 350rpx;
  left: 90rpx;
  position: relative;
  display: flex;
  justify-content: space-between;
}
.zhuce navigator {
  position: relative;
  left: 0rpx;
}

.xieyi {
  margin-left: 70rpx;
  left: 20rpx;
  width: 500rpx;
  display: flex;
  position: absolute;
  justify-content: center;
}
.xieyi .isXY {
  margin-left: 85rpx;
  position: relative;
  top: 10rpx;
  /* 修改复选框的大小 */
  transform: scale(0.6);
}
.xieyi .text-xy {
  margin-left: 10rpx;
  margin-top: 20rpx;
  color: #000000;
  font-size: 25rpx;
}
</style>
